<?php

namespace App\Http\Controllers\Home;

use App\Http\Requests\AddressRequest;
use App\Models\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AddressController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $addresses=auth()->user()->address()->get();
        return view('home.user.address',compact('addresses'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AddressRequest $request)
    {

//        dd($request->all());
        if(isset($request->is_default)){
            auth()->user()->address()->update(['is_default'=>0]);
        }
        auth()->user()->address()->create($request->all());
        return redirect()->route('home.address.index')->with('success','添加地址成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Address  $address
     * @return \Illuminate\Http\Response
     */
    public function show(Address $address)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Address  $address
     * @return \Illuminate\Http\Response
     */
    public function edit(Address $address)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Address  $address
     * @return \Illuminate\Http\Response
     */
    public function update(AddressRequest $request, Address $address)
    {
        if(isset($request->is_default)){
            auth()->user()->address()->update(['is_default'=>0]);
        }
        $address->update($request->all());
        return back()->with('success','更新成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Address  $address
     * @return \Illuminate\Http\Response
     */
    public function destroy(Address $address)
    {
        $address->delete();
        return back()->with('success','删除成功');
    }

    public function setDefault(Address $address){
        // 设置所有地址都不是默认地址
        auth()->user()->address()->update(['is_default'=>0]);
        // 设置当前地址为默认地址
        $address->update(['is_default'=>1]);
        // 返回成功提示
        return back()->with('success','设置成功');
    }
}
